#!/usr/bin/env python
# -*- coding: utf-8 -*-

# define level  no/all/critical/warn/
# none  不打印不记录
# no  不输出，记录到文件
# all 打印所有信息，记录到文件
# critical  打印重要的信息以及warn信息，记录到文件
# warn     打印警告信息，记录到文件
__author__ = 'dalon'
import sys, os
from datetime import datetime


class logger(object):
    def __init__(self, logfile, level):
        self.levels = {'none': -1, 'no': 0, 'warn': 1, 'critical': 2, 'all': 10}
        if level not in self.levels.keys():
            sys.exit()
        self.level = self.levels[level]
        if self.level >= 0:
            if not os.path.exists('log'):
                os.mkdir('log')
            if self.level != -1:
                self.logfile = open('.%slog%s' % (os.sep, os.sep) + logfile, 'a+')
        else:
            pass

    def log_no(self, msg):
        # level 0
        self.record(str(datetime.now()) + '    ' + msg)

    def log_warn(self, msg):
        # level 1
        if self.level >= 1:
            print str(datetime.now()) + '  WARN        ' + msg
        self.record(str(datetime.now()) + '  WARB        ' + msg)

    def log_critical(self, msg):
        # level 2, 1
        if self.level >= 2:
            print str(datetime.now()) + '  CRITICAL    ' + msg
        self.record(str(datetime.now()) + '  CRITICAL    ' + msg)

    def log_all(self, msg):
        # level 10, ... 2, 1
        if self.level >= 10:
            print str(datetime.now()) + '  INFO        ' + msg
        self.record(str(datetime.now()) + '  INFO        ' + msg)

    def record(self, msg):
        if self.level >= 0:
            self.logfile.write(msg + '\n')
            self.logfile.flush()
        else:
            pass

    def exit(self):
        if self.level >= 0:
            self.logfile.close()
        else:
            pass


if __name__ == '__main__':
    a = logger('result1.txt', 'all')
    a.log_no('log no')
    a.log_warn('log warn')
    a.log_critical('log crtical')
    a.log_all('log all')
    a.exit()
